<template>
  <div v-loading="loading">
    <div v-show="kind==='list'">
      <el-button @click="add" type="primary" size="small">添加</el-button>
      <el-button type="primary" size="small">批量导入</el-button>
      <car-list @edit="edit" @del="del"></car-list>
    </div>
    <div v-show="kind==='edit'">
      <car-edit :car="currentCar" @submitEdit="submitEdit" @cancelEdit="cancelEdit"></car-edit>
    </div>
  </div>
</template>

<script>
  import CarList from './subs/CarList.vue';
  import CarEdit from './subs/CarEdit.vue';
  import * as actionTypes from '../../constants/action-types';
    export default {
        name: 'Car',
      components:{
          CarList,
          CarEdit,
      },
        data() {
            return {
              loading: false,
              kind: 'list', // list, edit
              currentCar: null,
            }
        },
      computed:{

      },
      created(){
        this.fetchData();
      },
      methods:{
          fetchData(){
            let me =this;
            me.loading=true;
            this.$store.dispatch(actionTypes.GET_CARLIST).then(()=>{
              me.loading=false
            }).catch(() => {
              me.loading=false
            })
          },
        add(){
            this.kind='edit';
            this.currentCar=null;
        },
        edit(row){
          this.kind='edit';
          this.currentCar=row;
        },
        del(row){
          let me = this;
          this.$confirm('确定要删除吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            me.loading=true;
            me.$store.dispatch(actionTypes.DELETE_CAR, row.id).then(()=>{
              me.loading=false
            }).catch(() => {
              me.loading=false;
            })
          }).catch(() => {
          });
        },
        submitEdit(newCar){
          let me = this;
          me.loading=true;
          this.$store.dispatch(newCar.id?actionTypes.EDIT_CAR:actionTypes.ADD_CAR, newCar).then(()=>{
            me.kind='list';
            me.loading=false
          }).catch(() => {
            me.loading=false;
          })
        },
        cancelEdit(){
          this.kind='list';
        }
      }
    }
</script>

<style lang="stylus" scoped>
</style>
